#ifndef _SPAWN_MANANGER_H_
#define _SPAWN_MANANGER_H_

#include "Common.h"
#include "Resource.h"
#include "ResourceManager.h"
#include "Singleton.h"
#include "String.h"
#include "NGLog.h"
#include "Threading/ThreadStarter.h"
#include "Threading/QueueThreadPool.h"


class SpawnPtr;

class  SpawnManager:public ThreadRunableBase, public ResourceManager,public Singleton<SpawnManager>
{
public:
	SpawnManager();
	~SpawnManager();

	String	getSpawnStringName(const uint32 & serial);
	
	ResourcePtr  create(const uint32 & serial,const NameValuePairList* params = 0);
	ResourceCreateOrRetrieveResult  \
		createOrRetrieve(const uint32 & serial,const NameValuePairList* params = 0);
	ResourcePtr  load(const uint32 & serial);

	//user manager start
	void	Startup(const uint32 & gid,bool isBattle = true);
	void 	Shutdown(void);


	//根据查询，返回符合条件的记录 offset 为翻页起点 limitcount 为取回角色最大数量 query 为查询条件在 WHERE之后
	bool	getSpawnsList(std::list<SpawnPtr> * chars,const uint32 & offset,const uint32 & limitcount,const char * query,...);

	//根据查询条件返回一个查询结果数量 query 为在WHERE之后的SQL语句
	uint32	getDBCount(const char * query,...);

	//用于得到一个Mail结构，用于向数据库追加新效果的记录
	Resource * newDumySpawn(void);
	void	freeDumySpawn(Resource * dumy);

	//根据模板向数据库插入新的记录，返回插入的记录
	ResourcePtr	createSpawnDatabase(Resource * dumy);
	ResourcePtr	loadSpawnDatabase(Resource * dumy);



	//virual from  ThreadRunableBase
        bool  run(void *p);

	//得到再生区域的所有对象
	size_t getSpawnList(std::list<ResourcePtr> & cList);

	//处理再生线程 暂时用一个线程处理
	bool	StartSpawnProcess(void);


	const bool  & isBattleServer(void)	{	return m_battle_server;	}

	void	setSpawnCheck(const bool & set)	{	m_autoSpawnCheck = set;	}
protected:
	uint32		m_default_gid;
	String		m_default_group;
	bool		m_battle_server;
	bool		m_autoSpawnCheck;


	//the auto process channel queue pool
        CQueueThreadPool<uint32>     m_spawnProcessPool;


       /// @copydoc ResourceManager::createImpl
        Resource* createImpl(const String& name, ResourceHandle handle,
            const String& group, bool isManual, ManualResourceLoader* loader,
            const NameValuePairList* createParams);
};

//自动处理Spawn
class SpawnThread : public ThreadBase
{       
        SpawnManager  * rm;
public: 
        SpawnThread(SpawnManager * s) :ThreadBase("SpawnThread"),rm(s) {}
        bool run()
        {
		Log.Success("SpawnThread","Spawn Process thread start.");       
                return rm->StartSpawnProcess();
        }
};


#define   sSpawnMgr   SpawnManager::getSingleton()



#endif
